package com.jinxin.platform.cdacsfacetalk.rpc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.base.common.pojo.InvokeCfg;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.base.common.support.BusinessDelegate;
import com.jinxin.platform.cdacsfacetalk.bean.DeviceInfo;
import com.jinxin.platform.cdacsfacetalk.bean.ParsedDownResult;
import com.jinxin.platform.cdacsfacetalk.common.Constant;
import com.jinxin.platform.cdacsfacetalk.common.HouseInfo;
import com.jinxin.platform.cdacsfacetalk.common.SysOrgInfo;
import com.jinxin.platform.cdacsfacetalk.common.SysUserVO;
import com.jinxin.platform.cdacsfacetalk.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.alibaba.fastjson.JSON.toJSONString;

/**
 * @description: (描述...)
 * @return:
 * @author: Linn
 * @time: 2020/05/18
 */
@Component
@Slf4j
public class AcsFaceTalkRpc {
    @Autowired
    private BusinessDelegate businessDelegate;

    /**
     * 根据房间id(房间号)获取房间信息
     *
     * @return SysUser
     */
    public List<HouseInfo> getHouseInfoByRoomId(String roomId) {
        if(StringUtils.isEmpty(roomId)){return null;}
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(Constant.MODULE_KEY);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName("getHouseInfoByRoomId");
        HashMap<String, String> map = new HashMap<>();
        map.put("roomId",roomId);
        cfg.setArgs(map);
        JsonResult result = businessDelegate.invoke(cfg);
        if (result.getSuccess()) {
            if (result.getData() == null) {
                return null;
            }
            log.info("getHouseInfoByRoomId:" + result.getData());
            return JSON.parseArray(toJSONString(result.getData()), HouseInfo.class);
        }
//        else {
//            HouseInfo houseInfo = new HouseInfo();
//            houseInfo.setOpenId("op4RpweSZf975ahRfbQwshwu-bu8");//自己的测试号
//            //houseInfo.setUserId("1001");
//            houseInfo.setFullRoomInfo("海洋社区1栋2单元205");
//            return houseInfo;
//        }
        return null;
    }

    /**
     *
     * @param mac 注意是小写的
     * @return
     */
    public DeviceInfo getDeviceTypeByMac(String mac) {
        if(StringUtils.isEmpty(mac)){return null;}
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(Constant.MODULE_KEY);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName("getDeviceTypeByMac");
        HashMap<String, String> map = new HashMap<>();
        map.put("mac",mac);
        cfg.setArgs(map);
        JsonResult result = businessDelegate.invoke(cfg);
        if (result.getSuccess()) {
            if (result.getData() == null) {
                return null;
            }
            log.info("getDeviceTypeByMac:" + result.getData());
            return JSON.parseObject(toJSONString(result.getData()), DeviceInfo.class);
        }
        return null;
    }
    /**
     * 获取当前用户对象
     *
     * @return SysUser
     */
    public SysUserVO getCurrentUser() {
        JsonResult result = getJsonResult(Constant.MODULE_KEY,"getCurrentUser");
        if (result.getSuccess()) {
            if (result.getData() == null) {
                return null;
            }
            log.info("getCdcomplaintmgrCurrentUser:" + result.getData());
            return JSON.parseObject(toJSONString(result.getData()), SysUserVO.class);
        }
//        else {
//            SysUserVO userVO = new SysUserVO();
//            userVO.setUserId("1");
//            userVO.setUserAccount("admin");
//            userVO.setUserName("admin");
//            return userVO;
//        }
        return null;
    }

    /**
     * 获取当前用户id获取所在组织
     *
     * @return SysUser
     */
    public SysOrgInfo getCurrentOrg() {
        SysUserVO currentUser = getCurrentUser();
        if(currentUser == null){return null; }
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(Constant.MODULE_KEY);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName("getCurrentOrg");
        HashMap<String, String> map = new HashMap<>();
        map.put("userId",currentUser.getUserId());
        cfg.setArgs(map);
        JsonResult result = businessDelegate.invoke(cfg);
        if (result.getSuccess()) {
            if (result.getData() == null) {
                return null;
            }
            log.info("getCurrentOrg:" + result.getData());
            return JSON.parseObject(toJSONString(result.getData()), SysOrgInfo.class);
        }
//        else {
//            SysOrgInfo userVO = new SysOrgInfo();
//            userVO.setOrgId("1");
//            userVO.setOrgName("一个牛逼的公司");
//            return userVO;
//        }
        return null;
    }

    private JsonResult getJsonResult(String keyName,String funName) {
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(keyName);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName(funName);
        return businessDelegate.invoke(cfg);
    }

    public JsonResult remoteOpenDoor(String serialNum,String productCode) {
        if(StringUtils.isEmpty(serialNum)){
            return JsonResult.error("设备序列号不存在");
        }
        if(StringUtils.isEmpty(productCode)){
            return JsonResult.error("产品编号不存在");
        }
        ParsedDownResult downParams = new ParsedDownResult();
        downParams.setAppCode(Constant.APP_CODE);
        downParams.setAppVersion(Constant.APP_VERSION);
        downParams.setControlParams("{}");
        downParams.setFuncCmd("openDoor");
        downParams.setFuncCode("M1");
        downParams.setOperation("open door");
        downParams.setProductCode(productCode);
        JsonResult result = controlDevice(serialNum, downParams);
        log.info("remoteOpenDoor: " + result.toString());
        if (result.getSuccess()) {
            log.info("远程开门: "+ result.getData().toString());
            String resultJson = result.getData().toString();
            if(!StringUtils.isEmpty(resultJson)){
                JSONObject returnJson = JSONObject.parseObject(resultJson);
                String code = returnJson.getString("code");
                if("0".equals(code)){
                    return JsonResult.ok("远程开门成功",result.getData());
                }
            }
            return JsonResult.error("开门失败");
        }else {
            return JsonResult.error("开门失败");
        }
    }

    /**
     * 应用请求解析下行或上行
     * @param funcCode 应用产品编号 00073601
     * @param funcCmd 应用功能指令 如M1
     * @param controlParams 下行或下行控制参数
     * @param type down 下行 up 上行
     * @return
     */
    public JsonResult parseResult(String funcCode, String funcCmd, String controlParams, String type, String productCode){
        log.info("parseResult===== funcCode: " + funcCode + ", funcCmd: " + funcCmd + ", controlParams: " + controlParams);
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(Constant.MODULE_KEY);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName("parseResult");
        Map<String, Object> argsMap = setCommonArgsMap();
        argsMap.put("funcCode",funcCode);
        argsMap.put("productCode",productCode);
        argsMap.put("funcCmd",funcCmd);
        JSONObject paramJson = JSONObject.parseObject(controlParams);
        if("down".equals(type)){
            argsMap.put("controlParams",paramJson);
        }else if("up".equals(type)){
            argsMap.put("resultContent",paramJson);
        }else if("report".equals(type)){
            argsMap.put("reportMessage",paramJson);
            argsMap.put("cmd_name",funcCmd);
            argsMap.remove("funcCode");
            argsMap.remove("funcCmd");
        }
        cfg.setArgs(argsMap);
        log.info("parseResult argsMap: " + argsMap.toString());
        JsonResult result = businessDelegate.invoke(cfg);
        log.info("parseResult: funcCmd " +funcCmd + ". Result: " + result.toString());
        if (result !=null && result.getSuccess()) {
            return result;
        }
        return null;
    }

    private Map<String, Object> setCommonArgsMap(){
        HashMap<String, Object> argsMap = new HashMap<>();
        argsMap.put("appCode",Constant.APP_CODE);
        argsMap.put("appVersion",Constant.APP_VERSION);
        return argsMap;
    }

    private JsonResult controlDevice(String serialNum, ParsedDownResult downResult) {
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(Constant.MODULE_KEY);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName("controlDevice");
        Map<String, Object> map = new HashMap<>();
        map.put("operation", downResult.getOperation());
        map.put("serialNum", serialNum);
        String controlParams = downResult.getControlParams();
        map.put("controlParams", controlParams);
        cfg.setArgs(map);
        log.info("控制设备的参数: " + controlParams);
        return businessDelegate.invoke(cfg);
    }

}
